﻿//this file was only licensed within a separate project,
//TreeN was licensed as a project and has been pulled out of this application due to conflicting communication
//it would be onerous to rebuild WowoGeometry and the other graphics projects licensed to CyberneticImmortality.com
//so hopefully communication can be obtained for licensing a 3d graphics addon for this project.
using System;
using System.Net;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
using Microsoft.Win32;

namespace FileHelper
{
    public class FileIO<T>
    {
        public OpenFileDialog openFileDialog1 = new OpenFileDialog();
        public SaveFileDialog saveFileDialog1 = new SaveFileDialog();
        public String lastUsedFileName="";
        
        public void Open(ref T InData)
        {
            if (openFileDialog1.ShowDialog() == true)
            {
                OpenWithKnownFilename(ref InData, openFileDialog1.FileName);
            }
            lastUsedFileName = openFileDialog1.FileName;
            return;
        }

        public void Save(ref T InApp)
        {
            Save(ref InApp, lastUsedFileName);
        }

        public void Save(ref T InApp, String path)
        {
            if (path == "")
            {
                SaveAs(ref InApp);
            }
            else
            {
                SaveWithKnownFilename(InApp, path);
            }

        }

        public String Filter
        {
            set
            {
                openFileDialog1.Filter = "Symbolic Computation Application Files (*.sca)|*.sca";
                saveFileDialog1.Filter = "Symbolic Computation Application Files (*.sca)|*.sca";
            }
        }

        public void SaveAs(ref T InApp)
        {
            if (saveFileDialog1.ShowDialog() == true)
            {
                SaveWithKnownFilename(InApp, saveFileDialog1.FileName);
            }
            lastUsedFileName = saveFileDialog1.FileName;
            return;
        }

        public void OpenWithKnownFilename(ref T InApp, String InFileName)
        {
            XmlSerializer lSerializer = new XmlSerializer(InApp.GetType());
            XmlReader xr = XmlReader.Create(InFileName);
            InApp = (T)lSerializer.Deserialize(xr);
        }

        public void SaveWithKnownFilename(T InApp, String FileName)
        {
            XmlSerializer lSerializer = new XmlSerializer(InApp.GetType());
            XmlWriter lWriter = XmlWriter.Create(FileName);
            lSerializer.Serialize(lWriter, InApp);
        }

    }
}
